from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from users.models import User


class QQRegisterSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)

    def validate(self, attrs):
        # 校验openid
        access_token = attrs['access_token']
        openid = OAuthQQUser.check_save_user_token(access_token)
        if openid is None:
            raise serializers.ValidationError('无效的token')
        attrs['openid'] = openid

        # 校验短信验证码
        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('短信验证码错误')

        # 校验用户是否注册
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            password = attrs['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        user = validated_data.get('user')
        if not user:
            user = User.objects.create(
                username=validated_data.get('mobile'),
                password=validated_data.get('password'),
                mobile=validated_data.get('mobile')
            )
            user.set_password(validated_data['password'])
            user.save()

        # 保存QQ授权数据openid
        OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )
        return user
